package compress

import (
	"archive/zip"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/garyburd/redigo/redis"
)

func Scan(root string) {
	c, _ := redis.Dial("tcp", ":6379")
	defer c.Close()
	lenght, _ := redis.Int(c.Do("SCARD", "sora:qzip"))
	for i := 0; i < lenght; i++ {
		vid, err := redis.String(c.Do("SPOP", "sora:qzip"))
		if err != nil {
			log.Fatal(err)
		}
		println(root + "/" + vid)
		IWalk(root + "/" + vid)
	}
}

// 压缩一卷
// 目前貌似url不能以/结尾
func IWalk(url string) {
	// 先取得卷ID
	_, filename := filepath.Split(url)
	var file *os.File
	file, err := os.OpenFile(url+"/"+filename+".zip", os.O_RDWR|os.O_TRUNC, 0744)
	if err != nil && os.IsNotExist(err) { // 不存在则创建
		file, _ = os.OpenFile(url+"/"+filename+".zip", os.O_RDWR|os.O_TRUNC|os.O_CREATE, 0744)
	}
	defer file.Close()
	zw := zip.NewWriter(file)
	defer zw.Close()
	filepath.Walk(url, func(ipath string, iinfo os.FileInfo, ierr error) error {
		ts := strings.Split(ipath, filename+"/")
		if iinfo.Size() == 0 && !iinfo.IsDir() {
			return nil
		}
		if iinfo.IsDir() {
			zh := new(zip.FileHeader)
			zh.Name = ts[len(ts)-1] + "/"
			zh.UncompressedSize = 0
		} else {
			fr, _ := os.Open(ipath)
			defer fr.Close()
			srcInfo, _ := fr.Stat()
			zh, _ := zip.FileInfoHeader(srcInfo)
			zh.Name = ts[len(ts)-1]
			f, _ := zw.CreateHeader(zh)
			b := make([]byte, iinfo.Size())
			fr.Read(b)
			if _, err := f.Write(b); err != nil {
				log.Fatal(err)
			}
		}
		return nil
	})
}
